package org.aplikator.server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.MimeTypeParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.aplikator.client.widgets.BinaryFieldWidget;
import org.aplikator.server.descriptor.Entity;
import org.aplikator.server.descriptor.Property;
import org.aplikator.server.persistence.PersisterFactory;
import org.aplikator.shared.data.BinaryData;

public class FileDownloadServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    // private static final Logger LOG =
    // Logger.getLogger(FileDownloadServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String entityId = req.getParameter(BinaryFieldWidget.ENTITY_ID);
        String propertyId = req.getParameter(BinaryFieldWidget.PROPERTY_ID);
        int primaryKey = Integer.parseInt(req.getParameter(BinaryFieldWidget.PRIMARY_KEY_ID));
        int maxSize = Integer.parseInt(req.getParameter(BinaryFieldWidget.MAXSIZE_ID));
        Entity entity = (Entity) DescriptorRegistry.get().getDescriptionItem(entityId);
        @SuppressWarnings("unchecked")
        Property<BinaryData> property = (Property<BinaryData>) DescriptorRegistry.get().getDescriptionItem(propertyId);

        BinaryData blob = PersisterFactory.getPersister().getBlob(entity, property, primaryKey, maxSize);

        if (maxSize == BinaryFieldWidget.FULL_SIZE_CODE) {
            resp.setHeader("Content-disposition", "attachment; filename=" + blob.properties.get("filename"));
            resp.setContentType("application/octet-stream");
        } else {
            try {
                resp.setContentType(ImageResizer.getMimeType(blob.properties.get("filename")).toString());
            } catch (MimeTypeParseException e) {
                resp.setContentType("application/octet-stream");
            }
        }
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        OutputStream os = resp.getOutputStream();
        InputStream is = new ByteArrayInputStream(blob.data);

        Streams.copy(is, os, true);
        os.flush();
    }

}
